package cn.com.quickpay.web.servlet;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.URLEncoder;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;

import cn.com.quickpay.core.service.quick.QuickPay;
import cn.com.quickpay.core.util.DateUtil;

public class OrderPayServlet extends HttpServlet {
	
	private static final long serialVersionUID = 3184535180522475944L;
	
	/**
	 * 日志对象
	 */
	private final static Logger logger = LoggerFactory.getLogger(OrderPayServlet.class);
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		this.doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		String qryString = req.getQueryString();
		logger.info("qryString:"+qryString);
		logger.debug("method[{}]", new Object[] { req.getMethod() });
		logger.debug("agent[{}]", new Object[] { req.getHeader("user-agent") });
		
		Map<String, String[]> params = req.getParameterMap();
		JSONObject reqObj = new JSONObject();
		Map<String,String> map = new HashMap<String,String>();
		for (String key : params.keySet()) {
			String[] values = params.get(key);
			if (values.length > 0) {
				reqObj.put(key, values[0]);
				map.put(key, values[0]);
			}
		}
		try {
			HashMap<String, String> param = new HashMap<String, String>();
			param.put("out_trade_no", map.get("out_trade_no"));
			param.put("total_fee", map.get("total_fee"));
			param.put("order_time", map.get("order_time"));
			param.put("body", map.get("body"));
			param.put("client_ip", map.get("client_ip"));
			param.put("notify_url", map.get("notify_url"));
			param.put("time_expire", map.get("time_expire"));
			param.put("return_url", map.get("return_url"));
			param.put("attach", map.get("attach"));
			param.put("device_info", map.get("device_info"));
			String result =	new QuickPay().exec(param);
			JSONObject jsonObj = JSONObject.parseObject(result);
			String resp_code = jsonObj.getString("resp_code");
			if("000000".equals(resp_code)){
				String credential = jsonObj.getString("credential");
				req.setAttribute("credential", credential);
				String url = "jsp/middle.jsp";
				req.getRequestDispatcher(url).forward(req, resp);
			} else {
				logger.error("txn fail respCode[{}],respMsg[{}].", jsonObj.getString("resp_code"), jsonObj.getString("resp_msg"));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		
	}
	
	public static void main(String[] args) throws UnsupportedEncodingException{
		Map<String,String> map = new HashMap<String, String>();
		try {
			//必填参数
			map.put("orderCode", DateUtil.getCurrentDate14());
			map.put("totalAmount", "000000000012");
			map.put("subject", "test");
			map.put("payMode", "sand_h5");//快捷支付
			map.put("clientIp", InetAddress.getLocalHost().getHostAddress());
			map.put("notifyUrl", "http://paytest.shopping98.com/pay/apiNotify.shtml");
			map.put("frontUrl", "http://www.baidu.com");
			//非必填
			map.put("body", "test");
			map.put("txnTimeOut", "20170421000000");
			map.put("payExtra", "");
			map.put("storeId", "");
			map.put("terminalId", "");
			map.put("operatorId", "");
			map.put("bizExtendParams", "");
			map.put("merchExtendParams", "");
			map.put("extend", "");
			
		    //拼装参数Map为String，含URLEncode
		    StringBuffer paramstr = new StringBuffer();
		    for (Map.Entry<String, String> entry : map.entrySet()) {
		        paramstr.append(entry.getKey())
		                .append("=")
		                .append(URLEncoder.encode(entry.getValue(), "UTF-8"))
		                .append("&");
		    }
		    String param = paramstr.substring(0, paramstr.length() - 1);
//			System.out.println("http://localhost:8081/orderPay?"+param);
		    System.out.println("http://paytest.shopping98.com/sandpay/orderPay?"+param);
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

}
